package cn.itrigger.util;

import cn.itrigger.annotation.Property;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Properties;

/**
 * @author admin
 * @date 2018/5/16
 **/
public class PropertyUtil {

    public static Properties getProperties(File file) throws IOException {
        try (InputStream is = new FileInputStream(file);) {
            Properties p = new Properties();
            p.load(is);
            return p;
        }
    }

    public static <T> T parseProperties(File file, Class<T> claz) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        Properties properties = getProperties(file);
        Field[] fields = claz.getDeclaredFields();
        T instance = claz.newInstance();

        for (Field f : fields) {
            f.setAccessible(true);
            if (f.isAnnotationPresent(Property.class)){
                Property annotation = f.getAnnotation(Property.class);
                String property = properties.getProperty(annotation.value());

                if (StringUtils.isNotBlank(property)) {
                    f.set(instance,property);
                }else {
                    if (null != annotation.defaultValue()) {
                        f.set(instance,annotation.defaultValue());
                    }
                }
            }
        }

        return instance;
    }
}
